package com.oa.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oa.system.mapper.SysRoleMapper;
import com.oa.model.system.SysRole;
import com.oa.model.system.SysUserRole;
import com.oa.system.service.SysRoleService;
import com.oa.system.service.SysUserRoleService;
import com.oa.vo.system.AssginRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Admin
 * @title: SysRoleServiceImpl
 * @projectName Cloud_OA_Office
 * @description: SysRoleServiceImpl
 * @date 2024/10/1 16:00
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    //private SysUserRoleMapper sysUserRoleMapper;
    private SysUserRoleService sysUserRoleService;
    @Override
    public Map<String, Object> findRoleByAdminId(Long userId) {
        //查询所有角色
        List<SysRole> allRolesList = this.list();
        //根据用户id查询用户所拥有的角色id
        List<SysUserRole> existUserRoleList = sysUserRoleService.list(
                new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId)
                        .select(SysUserRole::getRoleId)
        );

        List<Long> existRoleIdList = existUserRoleList.stream()
                .map(c->c.getRoleId()).collect(Collectors.toList());

        //对角色进行分类
        List<SysRole> assignRoleList = new ArrayList<>();
        //根据查询所有角色id 返回角色信息
        for(SysRole sysRole : allRolesList) {
            //已分配
            if(existRoleIdList.contains(sysRole.getId())){
                assignRoleList.add(sysRole);
            }
        }

        Map<String,Object> roleMap = new HashMap<>();
        roleMap.put("assignRoleList",assignRoleList);
        roleMap.put("allRolesList",allRolesList);
        return roleMap;
    }
    @Transactional //事务
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,assginRoleVo.getUserId());

        sysUserRoleService.remove(wrapper);
        //sysUserRoleMapper.delete(wrapper);
        //重新进行分配
        for(Long roleId : assginRoleVo.getRoleIdList()){
            if(StringUtils.isEmpty(roleId)) continue;
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            //sysUserRoleMapper.insert(sysUserRole);
            sysUserRoleService.save(sysUserRole);
        }
    }
    //@Autowired
    //不用再导入mapper
}
